package com.okcl.security;

import cn.hutool.json.JSONUtil;
import com.okcl.dto.Result;
import com.okcl.utils.RedisClient;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
public class LogoutStatusSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private RedisClient redisClient;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("token");
        String key = "login:token:" + token;
        if (StringUtils.hasText(token)) {
            redisClient.del(key);
        }
        response.setContentType("application/json;charset=UTF-8");
        Result result = Result.ok("注销成功");
        response.getWriter().println(JSONUtil.toJsonStr(result));
    }
}
